package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String CART_PREFIX = "gulimall:cart:";

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;



    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)) {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> SkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1. 远程查询当前要添加的商品的信息
                R r = productFeignService.getSkuInfo(skuId);
                Object skuInfo = r.get("skuInfo");
                String s = JSON.toJSONString(skuInfo);
                SkuInfoVo skuInfoVo = JSON.parseObject(s, SkuInfoVo.class);


                cartItem.setCheck(true);
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                cartItem.setPrice(skuInfoVo.getPrice());
                cartItem.setCount(num);
                cartItem.setTitle(skuInfoVo.getSkuTitle());
                cartItem.setSkuId(skuInfoVo.getSkuId());
            }, executor);


            //查询sku的组合信息

            CompletableFuture<Void> skuAttr = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttr = productFeignService.getSkuSaleAttr(skuId);
                cartItem.setSkuAttr(skuSaleAttr);

            }, executor);

            CompletableFuture.allOf(SkuInfoFuture, skuAttr).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            return cartItem;
        } else {

            //购物车有此商品
            CartItem item = JSON.parseObject(o, CartItem.class);
            item.setCount(item.getCount() + num);

            cartOps.put(skuId.toString(), JSON.toJSONString(item));
            return item;

        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);

        return cartItem;
    }

    //获取购物车
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            //登录的购物车
            //还要合并之前没有登录的购物车
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserkey();

            List<CartItem> tempCartItem = getCartItem(CART_PREFIX + userInfoTo.getUserkey());
            if (tempCartItem != null) {
                for (CartItem cartItem : tempCartItem) {
                    addCart(cartItem.getSkuId(), cartItem.getCount());
                }
            }

            //清除临时购物车
            clearCart(tempCartKey);

            //获取登录后的购物车的数据
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);

        } else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserkey();
            List<CartItem> cartItem = getCartItem(cartKey);
            cart.setItems(cartItem);
        }

        return cart;
    }

    /**
     * 清空购物车
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    //勾选购物项
    @Override
    public void itemCheck(Long skuId, Integer checked) {

        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1 ? true : false);

        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), s);

    }

    //点击购物车数量的按钮
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);

        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    //删除购物车项
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> currentUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            String cartKey =  CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItem = getCartItem(cartKey);
            List<CartItem> collect = cartItem.stream().filter(item -> item.getCheck()).map(item -> {
                R price = productFeignService.getPrice(item.getSkuId());

                String price1 = (String) price.get("price");
                //更新最新价格
                item.setPrice(new BigDecimal(price1));
                return item;
            }).collect(Collectors.toList());

            return collect;

        }

    }


    //获取购物车的东西
    private List<CartItem> getCartItem(String cartKey) {
        BoundHashOperations<String, Object, Object> hashops = redisTemplate.boundHashOps(cartKey);

        List<Object> values = hashops.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);

                return cartItem;
            }).collect(Collectors.toList());

            return collect;
        }
        return null;
    }

    /**
     * 清空购物车
     *
     */


    /**
     * 获取到购物车的操作
     *
     * @return
     */

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserkey();
        }

        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        return ops;
    }
}
